package com.lagou.aop;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lagou.Utils.MyServletUtils;
import com.lagou.annotation.MyAutoPage;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import sun.reflect.generics.reflectiveObjects.ParameterizedTypeImpl;

import java.lang.reflect.Method;
import java.lang.reflect.Type;

/**
 * @program: springboot04_blog
 * @description: 分页方法处理。
 * @author: zhoushiduo
 * @create: 2020-12-15 10:05
 */

@Component
@Aspect
public class MyPageAop {
    @Pointcut("execution(* com.lagou.service.impl.*.*(..))")
    public void pointcut(){}

    @Before("pointcut()")
    public void beforePage(JoinPoint jp) throws NoSuchMethodException {
        //需要分页
        if(isAutoPage(jp)){
            //设置分页参数
            PageHelper.startPage(MyServletUtils.getLocalPageSysParm().getPageNum(), MyServletUtils.getLocalPageSysParm().getPageSize());
            System.out.println("设置分页参数：" + MyServletUtils.getLocalPageSysParm().getPageNum() + ","
                    +MyServletUtils.getLocalPageSysParm().getPageSize());
        }
    }

    @AfterReturning(value = "pointcut()" ,returning = "rtValue")
    public void afterPage(JoinPoint jp, Object rtValue) throws NoSuchMethodException {
        //需要分页
        if(isAutoPage(jp)){
            //清除分页控件
            PageHelper.clearPage();
            System.out.println("清除分页参数");
        }
    }

    /**
     * 是否需要自动分页
     * @param jp
     * @return
     * @throws NoSuchMethodException
     */
    private boolean isAutoPage(JoinPoint jp) throws NoSuchMethodException {
        //获取方法
        MethodSignature signature = (MethodSignature) jp.getSignature();
        Method method = signature.getMethod();
        //获取返回值类型
        Type t = method.getAnnotatedReturnType().getType();
        //判断是否为server服务组件
        if(!method.getDeclaringClass().isAnnotationPresent(Service.class)){
            return false;
        }
        //判断返回参数是否为分页类型
        if(PageInfo.class.getName().equalsIgnoreCase(((ParameterizedTypeImpl) t).getRawType().getName())){
            //判断该方法是否需要公共分页还是单独手动分页，通过添加注解
            boolean isAutoPage = true;
            if (method.isAnnotationPresent(MyAutoPage.class)) {
                isAutoPage = method.getAnnotation(MyAutoPage.class).value();
            }
            return isAutoPage;
        }
        return false;
    }
}
